<?php
/**
 * Created by PhpStorm.
 * User: LiuJiaJun
 * Date: 2018/11/18
 * Time: 21:07
 */

namespace service\file;

class FileLock implements Lock
{
    private $uuid;
    private $fp = null;
    private $errorPath = '';
    private $lockDefaultPath = '';
    private $rootPath = '';
    private $lockName = [
        0=>'preparation.txt',
        1=>'catGet.txt',
        2=>'catPut.txt',
        3=>'inventory.txt',
        4=>'feedPrepare.txt',
        5=>'feedAddMateriel.txt'
    ];
    const LOCK_TYPE_OUTPUT = 0;
    const LOCK_TYPE_CAR_GET = 1;
    const LOCK_TYPE_CAR_PUT = 2;
    const LOCK_TYPE_INVENTORY = 3;
    const LOCK_TYPE_FEED_PREPARE = 4;
    const LOCK_TYPE_MACHINE_ADD = 5;

    const ROOT_LOCK = 'data/data/lock/';
    const DEFAULT_LOCK_FILE = 'data/data/lock/lock.txt';
    const DEFAULT_ERROR_FILE = 'data/data/lock/error.txt';

    public function __construct($uuid)
    {
        $this->uuid = $uuid;
        $this->rootPath = CMF_ROOT . self::ROOT_LOCK;
        $this->errorPath = CMF_ROOT . self::DEFAULT_ERROR_FILE;
        $this->lockDefaultPath = CMF_ROOT . self::DEFAULT_LOCK_FILE;
    }

    public function lock($type = '')
    {
        if(isset($this->lockName[$type])){
            $path = $this->rootPath . $this->uuid . '/'. $this->lockName[$type];
        }else{
            $path = $this->lockDefaultPath;
        }
        $this->initDir($path);
        $fp = fopen($path, "w");
        $this->fp = $fp;
        if(!flock($fp,LOCK_EX )) {
            file_put_contents($this->errorPath,get_current_time()."：加锁失败\r\n",FILE_APPEND);
        }
    }

    public function unlock()
    {
        //文件解锁
        if(null != $this->fp){
            flock($this->fp,LOCK_UN);
            fclose($this->fp);
        }
    }

    /**
     * 处理文件夹不存在的情况
     *
     * @param $path
     */
    private function initDir($path){
        $dirname = dirname($path);
        //如果文件不存在
        if (!file_exists($path)){
            //如果文件夹不存在
            if(!is_dir($dirname)){
                mkdir($dirname,0777,true);
            }
        }
    }


}